package com.everflourish.yeah100.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.questionlib.QuestionBankDetailActivity;
import com.everflourish.yeah100.entity.question.CancelQuestion;
import com.everflourish.yeah100.entity.question.Question;
import com.everflourish.yeah100.http.ImageRequest;
import com.everflourish.yeah100.ui.CircleImageView;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/29.
 * 时间：2016/7/29
 */
public class QuestionBankDetailAdapter extends RecyclerView.Adapter<QuestionBankDetailAdapter.QuestionBankDetailHolder> {

    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private ArrayList<Question> mList;
    private ImageRequest imageRequest;
    private RequestQueue mQueue;
    private LoadDialog mLoadDialog;
    private QuestionBankDetailActivity mActivity;
    private String mTagId;

    public QuestionBankDetailAdapter(Context mContext, List<Question> mList,
                                     QuestionBankDetailActivity mActivity, String mTagId) {
        this.mContext = mContext;
        this.mList = (ArrayList<Question>) mList;
        this.mActivity = mActivity;
        this.mTagId = mTagId;
        mLayoutInflater = LayoutInflater.from(mContext);
        mQueue = Volley.newRequestQueue(mContext);
        imageRequest = ImageRequest.getInstance(mQueue);
    }

    @Override
    public QuestionBankDetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mLayoutInflater.inflate(R.layout.item_question_bank_detail, parent, false);
        QuestionBankDetailHolder viewHolder = new QuestionBankDetailHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(QuestionBankDetailHolder holder, final int position) {
        Question question = mList.get(position);
        holder.seqNo.setText(question.getSeqNo());
        if (question.getComment() == null) {
            question.setComment("");
        }
        String comment = "<b>题目分析：</b>" + question.getComment();
        holder.questionCommentTv.setText(Html.fromHtml(comment));
        if (!question.getQuestionType().equals("3")) {  // 非主观题
            if (question.getAnswer().equals("")) {
                holder.questionStandardAnswerTv.setText("标准答案：无");
            } else {
                holder.questionStandardAnswerTv.setText("标准答案：" + question.getAnswer());
            }
        } else {
            holder.questionStandardAnswerTv.setVisibility(View.GONE);
        }
        QuestionImageAdapter questionImageAdapter = new QuestionImageAdapter(mContext, question.getImageUrls());
        holder.imageRcv.setLayoutManager(new LinearLayoutManager(mContext));
        holder.imageRcv.setAdapter(questionImageAdapter);
        holder.deleteIv.setOnClickListener(new MyOnclickListener(holder, position, questionImageAdapter));
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public class QuestionBankDetailHolder extends RecyclerView.ViewHolder {

        private CircleImageView questionHeadCv;
        private TextView userNameTv;
        private TextView seqNo;
        private TextView questionCommentTv;
        private TextView questionStandardAnswerTv;
        private RecyclerView imageRcv;
        private ImageView deleteIv;

        public QuestionBankDetailHolder(View itemView) {
            super(itemView);
            questionHeadCv = (CircleImageView) itemView.findViewById(R.id.question_bank_user_image);
            userNameTv = (TextView) itemView.findViewById(R.id.question_bank_user_name_tv);
            seqNo = (TextView) itemView.findViewById(R.id.question_bank_number_tv);
            questionCommentTv = (TextView) itemView.findViewById(R.id.question_bank_statistic_tv);
            questionStandardAnswerTv = (TextView) itemView.findViewById(R.id.question_standard_answer);
            imageRcv = (RecyclerView) itemView.findViewById(R.id.question_bank_capture_list);
            deleteIv = (ImageView) itemView.findViewById(R.id.item_question_bank_delete);
        }
    }

    class MyOnclickListener implements View.OnClickListener {

        private QuestionBankDetailHolder viewHolder;
        private int position;

        public MyOnclickListener(QuestionBankDetailHolder viewHolder, int position, QuestionImageAdapter questionImageAdapter) {
            this.viewHolder = viewHolder;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.item_question_bank_delete:
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setMessage("确定要删除该题目吗？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            unFavoriteQuestionRequest(setCancelQuestionList(mList.get(position)), position);
                        }
                    });
                    builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                    break;
            }
        }
    }

    /**
     * 设置取消的参数
     *
     * @param question
     * @return
     */
    private List<CancelQuestion> setCancelQuestionList(Question question) {
        List<CancelQuestion> cancelQuestions = new ArrayList<CancelQuestion>();
        CancelQuestion cancelQuestion = new CancelQuestion();
        cancelQuestion.setQuestionId(question.getQuestionId());
        List<String> tagIds = new ArrayList<>();
        tagIds.add(mTagId);
        cancelQuestion.setTagIds(tagIds);
        cancelQuestions.add(cancelQuestion);
        return cancelQuestions;
    }

    /**
     * 老师取消收藏题目请求
     *
     * @param cancelQuestions
     * @param position
     */
    private void unFavoriteQuestionRequest(List<CancelQuestion> cancelQuestions, final int position) {
        mLoadDialog = LoadDialog.show(mContext, null, "删除中...", mQueue);
        JsonObjectRequest request = mActivity.mRequest.unFavoriteQuestionRequest(cancelQuestions,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        unFavoriteQuestionListener(response, position);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mActivity.mRequest.disposeError(mContext, mLoadDialog, error, "删除题目失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 老师删除题库中的题目监听
     *
     * @param response
     */
    private void unFavoriteQuestionListener(JSONObject response, int position) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                mList.remove(position);
                mActivity.isUpdate = true;
                notifyDataSetChanged();
                MyToast.showShort(mContext, "删除题目成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09191_000001E);
            } else if (resultCode.equals(ResultCode.result_300025E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09192_300025E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091999_999999E);
            } else {
                MyToast.showShort(mContext, "删除题目失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "删除题目失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

}